package view

import (
	"cloudops/src/common"
	"cloudops/src/config"
	"cloudops/src/models"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
	"go.uber.org/zap"
	"strconv"
)

// 添加表单设计
func createFormDesign(c *gin.Context) {
	sc := c.MustGet(common.GIN_CTX_CONFIG_CONFIG).(*config.ServerConfig)
	var reqObj models.FormDesign
	err := c.BindJSON(&reqObj)
	if err != nil {
		sc.Logger.Error("createFormDesign failed",
			zap.Any("err", reqObj), zap.Error(err),
		)
		common.FailWithMessage(err.Error(), c)
		return
	}
	err = validate.Struct(reqObj)
	if err != nil {
		if errors, ok := err.(validator.ValidationErrors); ok {
			common.ReqBadFailWithWithDetailed(
				gin.H{
					"翻译前": err.Error(),
					"翻译后": errors.Translate(trans),
				},
				"请求出错",
				c,
			)
			return
		}
		common.ReqBadFailWithMessage(err.Error(), c)
		return
	}
	userName := c.MustGet(common.GIN_CTX_JWT_USER_NAME).(string)
	dbUser, err := models.GetUserByUserName(userName)
	if err != nil {
		sc.Logger.Error("通过token解析到的userName去数据库中找User失败", zap.Error(err))
		common.FailWithMessage(err.Error(), c)
		return
	}
	reqObj.UserID = dbUser.ID

	// 下面级联创建
	err = reqObj.CreateOneFormDesign()
	if err != nil {
		sc.Logger.Error("新增表单设计数据库失败",
			zap.Any("reqObj", reqObj),
			zap.Error(err))
		common.FailWithMessage(err.Error(), c)
		return
	}
	common.OkWithMessage("创建成功", c)
}

// 获取所有的表单
func getFormDesignList(c *gin.Context) {
	sc := c.MustGet(common.GIN_CTX_CONFIG_CONFIG).(*config.ServerConfig)
	currentPage, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	pageSize, _ := strconv.Atoi(c.DefaultQuery("pageSize", "100"))

	offset := 0
	limit := 0
	limit = pageSize
	if currentPage > 1 {
		offset = (currentPage - 1) * limit
	}
	//这里只能新增 不能去掉，因为是 多种资源共用的query
	searchUserID := c.DefaultQuery("UserID", "")
	searchUserIDInt, _ := strconv.Atoi(searchUserID)
	searchName := c.DefaultQuery("name", "")

	// 数据库拿所有的表单设计
	objs, err := models.GetFormDesignAll()
	if err != nil {
		sc.Logger.Error("获取表单设计失败", zap.Any("objs", objs), zap.Error(err))
		common.ReqBadFailWithMessage(fmt.Sprintf("获取表单设计失败：%v", err.Error()), c)
		return
	}

	allIds := []int{}
	for _, obj := range objs {
		obj := obj
		// 过滤
		if searchName != "" && obj.Name != searchName {
			continue
		}

		if searchUserID != "" && int(obj.UserID) != searchUserIDInt {
			continue
		}
		allIds = append(allIds, int(obj.ID))
	}

	if len(allIds) == 0 {
		common.OkWithDetailed(allIds, "ok", c)
	}

	objs, err = models.GetFormDesignByIdsWithLimitOffset(allIds, limit, offset)
	if err != nil {
		sc.Logger.Error("获取表单设计失败", zap.Error(err))
		common.ReqBadFailWithMessage(fmt.Sprintf("获取表单设计失败：%v", err.Error()), c)
		return
	}

	for _, obj := range objs {
		obj := obj
		obj.FillFrontAllData()
	}
	resp := &ResponseResourceCommon{
		Total: len(allIds),
		Items: objs,
	}

	common.OkWithDetailed(resp, "获取表单成功", c)
}

// 删除表单
func deleteFormDesign(c *gin.Context) {
	sc := c.MustGet(common.GIN_CTX_CONFIG_CONFIG).(*config.ServerConfig)
	id := c.Param("id")
	sc.Logger.Info("删除表单设计", zap.Any("id", id))

	// 从数据库中查找ID这个对象
	intVar, _ := strconv.Atoi(id)
	dbObj, err := models.GetFormDesignById(intVar)
	if err != nil {
		sc.Logger.Error("删除表单设计失败", zap.Any("表单", id), zap.Error(err))
		common.FailWithMessage(fmt.Sprintf(err.Error()), c)
		return
	}
	dbTemplate, _ := models.GetWorkOrderTemplateByFormDesignId(intVar)
	if dbTemplate != nil {
		sc.Logger.Error("删除表单设计失败", zap.Any("表单", id), zap.Error(err))
		common.FailWithMessage("该表单已被工单模板使用，请先删除对应的工单模板", c)
		return
	}

	err = dbObj.DeleteOneFormDesign()
	if err != nil {
		sc.Logger.Error("删除表单设计失败", zap.Any("表单", id), zap.Error(err))
		common.FailWithMessage(err.Error(), c)
		return
	}

	common.OkWithMessage("删除成功", c)
}

// 更新表单
func updateFormDesign(c *gin.Context) {
	sc := c.MustGet(common.GIN_CTX_CONFIG_CONFIG).(*config.ServerConfig)
	var reqObj models.FormDesign
	err := c.ShouldBindJSON(&reqObj)
	if err != nil {
		sc.Logger.Error("更新表单设计失败", zap.Any("reqObj", reqObj), zap.Error(err))
		common.FailWithMessage(err.Error(), c)
		return
	}

	// 字段校验
	err = validate.Struct(reqObj)
	if err != nil {
		if errors, ok := err.(validator.ValidationErrors); ok {
			common.ReqBadFailWithWithDetailed(
				gin.H{
					"翻译前": err.Error(),
					"翻译后": errors.Translate(trans),
				},
				"请求出错",
				c,
			)
			return
		}
		common.ReqBadFailWithMessage(err.Error(), c)
		return
	}
	_, err = models.GetFormDesignById(int(reqObj.ID))
	if err != nil {
		sc.Logger.Error("更新表单设计失败", zap.Any("reqObj", reqObj), zap.Error(err))
		common.FailWithMessage(err.Error(), c)
		return
	}
	err = reqObj.UpdateOneFormDesign()
	if err != nil {
		sc.Logger.Error("更新表单设计失败", zap.Any("reqObj", reqObj), zap.Error(err))
		common.FailWithMessage(err.Error(), c)
		return
	}

	common.OkWithMessage("更新成功", c)
}
